import { Injectable, UnauthorizedException, Inject, ServiceUnavailableException } from '@nestjs/common';
// import { REQUEST } from '@nestjs/core';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { Strategy } from 'passport-local';
import { AuthService } from './auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'localStrategy') {
  constructor(
    private readonly authService: AuthService,
    // @Inject(REQUEST) private readonly request: Request
  ) {
    super({
      usernameField: 'username',
      passwordField: 'password',
    });
  }

  // 可通过上述 super 方法更改 username password 关键字段
  async validate(username: string, password: string): Promise<any> {
    try {
      const user = await this.authService.validateUser(username, password);
      if (!user) {
        throw new UnauthorizedException('用户名或密码错误');
      }
      return user;
    } catch (e) {
      throw new ServiceUnavailableException(e);
    }
  }
}
